<template>
  <!-- 头部 -->
  <!-- <van-nav-bar fixed title="搜索结果" left-arrow @click-left="$router.back()" /> -->
  <!-- 搜索 -->
  <div class="container">
    <!-- 导航固定定位 fixed -->
    <van-nav-bar
      fixed
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 文章列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      finished-text="没有更多了"
      :immediate-check="false"
    >
      <van-cell v-for="item in list" :key="item.art_id">
        <div class="article_item">
          <h3 class="van-ellipsis">
            {{ item.title }}
          </h3>
          <div class="img_box">
            <van-image
              :class="item.cover.type === 1 ? 'w100' : 'w33'"
              fit="cover"
              v-for="(img, i) in item.cover.images"
              :key="i"
              :src="img"
            />
          </div>
          <div class="info_box">
            <span>{{ item.aut_name }}</span>
            <span>{{ item.comm_count }}评论</span>
            <span>{{ item.pubdate | relTime }}</span>
          </div>
        </div>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
// 搜索文章
import { searchArticles } from '@/api/article.js'
export default {
  name: 'search-result',
  data () {
    return {
      list: [],
      loading: false, // 评论列表加载中状态(是否加载中)
      finished: false, // 评论列表完全加载完毕状态(是否加载完)
      n: 1
    }
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      try {
        // q 搜索关键字
        // console.log(this.$route)

        const { data } = await searchArticles({ page: this.n, per_page: 10, q: this.$route.query.q })
        // console.log('搜索文章列表: ', data)

        this.list.push(...data.results)
        // console.log('this.list: ', this.list)

        // 数据全部加载完成
        this.n++
        if (this.list.length === data.total_count) {
          // 加载状态结束
          this.finished = true
        } else {
          // 开启加载
          this.loading = false
        }
      } catch (error) {
        console.dir(error)
      }
    }
  },
  // ------------------ 手动获取列表数据 -----------------------
  // 只有路由缓存才有activated
  activated () {
    this.list = [] // 重置历史数据为默认
    this.finished = false // 数据还没有加载完
    this.loading = true // 关闭加载
    this.onLoad()
    // console.log(1)
  }
}
</script>

<style scoped lang='less'>
.container {
  padding-top: 46px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}
.article_item {
  h3 {
    font-weight: normal;
    line-height: 2;
  }
  .img_box {
    display: flex;
    justify-content: space-between;
    .w33 {
      width: 33%;
      height: 90px;
    }
    .w100 {
      height: 180px;
      width: 100%;
    }
  }
  .info_box {
    color: #999;
    line-height: 2;
    position: relative;
    span {
      padding-right: 10px;
    }
  }
}
</style>
